from flask import Blueprint,render_template,request,make_response,redirect,g
from model import *
import json
import hashlib
import re
from middleware import validate,Is_Blogger
from time import time
from settings import static_config,blog_name,labels,contact_content
def model():
	try:
		'''前端数据（data）'''
		data=json.loads(request.get_data().decode('utf-8'))
	except:
		response=make_response({"status":400,"message":"Invalid login"})
		response.status=403
		return response
	'''此处为selecr的sql语句，如是insert、delete、update等用ins_del_upd()函数'''
	ok,result=select('''sql''')
	if not ok:
		response=make_response(result)
		response.status=403
		return response
	if result:
		'''
		业务处理
		'''
		response=make_response({"code":200, "message":'''情况表明''',"data":'''数据'''})
		return response
	response=make_response({"code":400, "message":'''情况表明'''})
	return response

#!#####################################
html= Blueprint("html",__name__)#^网页组
@html.get('/login')#^登录页面
def login():
	return render_template('login.html',blogname=blog_name)
@html.get('/register')#^注册页面
def register():
	return render_template('register.html',blogname=blog_name)
@html.get('/index')#^首页
@validate
def index():
	ok,data=select("select * from article")
	if ok:
		return render_template('index.html',blogname=blog_name,articles=data,labels=labels,validate=g.Is_Blogger)
	else:
		return render_template('index.html',blogname=blog_name,articles={},labels=labels)#^如果查询出错则返回空列表
@html.get('/post')#^详情页
@validate
def post():
	try:
		kay=request.args.get('ArticleId')
	except Exception as e:
		return {"code":400,"message":"参数解析错误","erroe":e},403
	sql="select * from article"
	if kay:#^如果没有指定文章id则查询全部后返回第一个
		sql+=" WHERE ArticleId = '%s' " % kay
	ok,data=select(sql)
	if ok:
		print(labels)
		if data:
			return render_template('post.html',blogname=blog_name,article=data[0],labels=labels)
		else:
			return render_template('post.html',blogname=blog_name,article=[],labels=labels)
	else:
		return redirect('login')
@html.get('/about')#^关于我
@validate
def about():
	return render_template('about.html',blogname=blog_name,labels=labels)
@html.get('/contact')#^联系我
@validate
def contact():
	return render_template('contact.html',blogname=blog_name,labels=labels,contact_content=contact_content)
@html.get('/exit')#^退出登录
@validate
def exit():
	response=make_response(render_template('login.html'))#^响应登录页
	response.delete_cookie("Dom_cookie")#^删除前端cookie数据
	return response
@html.get('/release')#^文章发布页
@validate
@Is_Blogger
def release():
	return render_template('release.html',blogname=blog_name,labels=labels)

#!#####################################
user= Blueprint("user",__name__)#^用户组
@user.post("/login")#^登录
def login():
	try:#^确保前端数据以json格式传输
		data=json.loads(request.get_data().decode('utf-8'))#^json库解析json字符串
	except Exception as e:
		response=make_response({"status":400,"message":"Invalid login","e":e})
		response.status=403
		return response
	ok,result=select("select Password from users where UserId ={} and Password='{}'".format(data['UserId'],data['Password']))#^检验账号密码是否正确
	if not ok:#^sql执行错误放回失败
		print(result)
		response=make_response(result)
		response.status=403
		return response
	if result:
		response=make_response({"code":200, "message":"登录成功！","index_html":"/html/index"})#^登录成功后前端跳转index_html字段所指的页面
		response.status=200
		cookie=hashlib.md5(str(time()).encode(encoding='UTF-8')).hexdigest()
		ins_del_upd("update users  set Cookie='{}' where UserId={}".format(cookie,data['UserId']))#^将cookie值进行数据库存储
		response.set_cookie(key="Dom_cookie",value=cookie,max_age=3600,expires=time(),path='/',httponly=True)#^将cookie值写入前端
		return response
	response=make_response({"code":400, "message":"账号或密码错误！"})
	return response
@user.post("/register")#^注册
def register():
	try:
		data=json.loads(request.get_data().decode('utf-8'))
		if (not re.search(r'^\d+$',data['UserId'])) or (not re.search(r'^[a-zA-Z0-9]+$',data['Password'])):#^检查账号和密码的有效性
			return make_response({"code":400, "message": "账号或密码格式不正确！"})
		ok,result=select("select password from users where UserId ={}".format(data['UserId']))#^检查账号是否已经存在，存在则不可注册
		if not ok:
			response=make_response(json.dumps(result))#^sql语句执行失败返回错误信息
			response.status=403
			return response
		if not result:
			cookie=hashlib.md5(str(time()).encode(encoding='UTF-8')).hexdigest()#^通过md5加密时间戳字符串得到cookie字符串
			if ins_del_upd("insert into users(UserId,UserName,Password) value({},'{}','{}')".format(data['UserId'],data['UserName'],data['Password']))[0]:#^添加账号
				response=make_response({"code":200, "message":"注册成功！","Callback":"./html/index.html"})
				ins_del_upd("update users  set Cookie='{}' where UserId={}".format(cookie,data['UserId']))
				response.set_cookie(key="Dom_cookie",value=cookie,max_age=3600,expires=time(),path='/',httponly=True)#^给前端设置cookie
				return response
			else:
				response=make_response({"code":400, "message":"注册失败！"})
				return response
		response=make_response({"code":400, "message":"账号已存在！"})
		return response
	except Exception as e:
		print(e)
		response=make_response({"status":403,"message":"Invalid register"})
		response.status=403
		return response
	
#!#####################################
article= Blueprint("article",__name__)#^文章组
@article.post("/index")#^文章首页列表
@validate
@Is_Blogger
def index():
	ok,result=select("select * from article")#^查询全部列表
	if not ok:
		response=make_response(result)
		response.status=403
		return response
	if result:
		print(result)
		response=make_response({"code":200, "message":result})
		return response
	else:
		response=make_response({"code":200, "message":"数据为空"})
		return response
@article.post("/add")#^文章添加
@validate
@Is_Blogger
def add():
	try:
		'''前端数据（data）'''
		img=request.files['Img']#^解析dataform格式数据的文件数据
		data=request.form#^解析dataform格式的普通字段数据
	except:
		response=make_response({"status":400,"message":"Invalid login"})
		return response,403
	'''此处为selecr的sql语句，如是insert、delete、update等用ins_del_upd()函数'''
	filename=int(time())#^生成随机文件名
	filepath='./blog/img/{}.{}'.format(filename,img.filename.split('.')[1])#^生成文件的本地保存路径
	img.save(filepath)#^文件保存
	ok,result=ins_del_upd("insert into article(ArticleTitle,ArticleContent,ArticleImg) value('{}','{}','{}')".format(data['ArticleTitle'],data['ArticleContent'],static_config['static_url_path']+filepath[6:]))#^将文章信息写入数据库
	if not ok:
		print(result)
		response=make_response()
		return response,403
	if result['rowcount']>0:#^根据数据库返回的受影响行数断定是否上传成功
		response=make_response({"code":200, "message":"添加文章成功"})
		return response,200
	response=make_response({"code":400, "message":"添加文章失败"})
	return response,403
@article.get("/delete")#^文章删除
@validate
@Is_Blogger
def delete():
	try:
		kay=request.args.get('ArticleId')
	except Exception as e:
		return {"code":400,"message":"参数解析错误","erroe":e},403
	print(kay)
	ok,rowcount=ins_del_upd("delete from article where ArticleId={}".format(kay))
	if ok and rowcount['rowcount']>0:
		return {"code":200,"message":"删除成功","index_url":"/html/index"}
	return {"code":400,"message":"删除错误"}